import arcpy, os, sys
import xml.dom.minidom as DOM

arcpy.env.overwriteOutput = True

# define local variables
wrkspc = 'd:/'
mapDoc = arcpy.mapping.MapDocument(wrkspc + 'test1.mxd')
con = 'd:/app/arcgis.ags' 
service = 'ss'
sddraft = wrkspc + service + '.sddraft'
sd = wrkspc + service + '.sd'
summary = 'Population Density by County'
tags = 'county, counties, population, density, census'
newSDdraft=wrkspc + service + 'new.sddraft'

# create service definition draft
analysis = arcpy.mapping.CreateMapSDDraft(mapDoc, sddraft, service, 'ARCGIS_SERVER', 
                                          con, True, None, summary, tags)

#turn on DynamicLayers
doc = DOM.parse(sddraft)
configProps = doc.getElementsByTagName('ConfigurationProperties')[0]
propArray = configProps.firstChild
propSets = propArray.childNodes
for propSet in propSets:
    keyValues = propSet.childNodes
    for keyValue in keyValues:
        if keyValue.tagName == 'Key':
            if keyValue.firstChild.data == "enableDynamicLayers":
                keyValue.nextSibling.firstChild.data = "true"
# Write the new draft to disk
f = open(newSDdraft, 'w')
doc.writexml( f )
f.close()

# stage and upload the service if the sddraft analysis did not contain errors
if analysis['errors'] == {}:
    # Execute StageService
    arcpy.StageService_server(newSDdraft, sd)
    # Execute UploadServiceDefinition
    arcpy.UploadServiceDefinition_server(sd, con)
else: 
    # if the sddraft analysis contained errors, display them
    print analysis['errors']
